package com.ihrm.modules.sys.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.ihrm.common.exception.RRException;
import com.ihrm.common.utils.R;
import com.ihrm.common.utils.RedisUtils;
import com.ihrm.modules.sys.entity.UserEntity;
import com.ihrm.modules.sys.service.UserService;
import com.ihrm.modules.sys.shiro.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * 登录相关
 */
@Controller
@RequestMapping("/sys")
@Api(tags = "登录模块")
public class LoginController {
	@Autowired
	private Producer producer;

	@Autowired
	private UserService userService;

	@Autowired
	private RedisUtils redisUtils;

	@RequestMapping("/captcha")
	@ApiOperation("获取验证码")
	public void captcha(HttpServletResponse response) throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		// 生成文字验证码
		String text = producer.createText();
		// 生成图片验证码
		BufferedImage image = producer.createImage(text);
		// 保存到shiro session
//		 ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

		redisUtils.set(Constants.KAPTCHA_SESSION_KEY, text, 300);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
	}

	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping("/login")
	@ApiOperation("登录")
	public R login(@RequestBody Map<String, String> params) {

		String captcha = params.get("captcha");

		if(StringUtils.isBlank(captcha)){
			throw new RRException("验证码不为空",500);
		}
//		 String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
		String kaptcha = redisUtils.get(Constants.KAPTCHA_SESSION_KEY);
		if (!StringUtils.equalsIgnoreCase(captcha, kaptcha)) {
			return R.error("验证码不正确");
		}

		try {
			String mobile = params.get("mobile");
			String password = params.get("password");
			Subject subject = ShiroUtils.getSubject();
			UsernamePasswordToken token = new UsernamePasswordToken(mobile, password);
			subject.login(token);
		} catch (UnknownAccountException e) {
//			return R.error(e.getMessage());
			return  R.error("没有该权限,请联系管理员");
		} catch (IncorrectCredentialsException e) {
			return R.error("账号或密码不正确");
		} catch (LockedAccountException e) {
			return R.error("账号已被禁用,请联系管理员");
		} catch (AuthenticationException e) {
			return R.error("账户验证失败");
		}

		// 查询用户信息
		Session session = ShiroUtils.getSession();

		return R.ok().put("token", session.getId());
	}

	/**
	 * 退出
	 */
	@RequestMapping("/logout")
	@ResponseBody
	@ApiOperation("退出")
	public R logout() {
		ShiroUtils.logout();
		return R.ok();
	}

	@ResponseBody
	@RequestMapping("/getInfo")
	@ApiOperation("获取用户信息")
	public R getInfo(String token) {
		UserEntity entity = ShiroUtils.getUserEntity();
		System.out.println(entity);
		if (null == entity || entity.getId() == null) {
			throw new RRException("该用户不存在");
		}
		Map<String, Object> userInfo = userService.profile(entity);
		return R.ok().put("userInfo", userInfo);
	}

}
